package com.fr.lavollepic.gbdroid;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;

public class homeactivity extends Activity implements OnClickListener {
 

/* --------------------------------------------- VARIABLES GLOBALES ----------------------------------------------- */
	// boutons de lecture
	private Button playstream;	
	private Button stopstream;
	//player
	private MediaPlayer mp;

	//controle du volume
	private AudioManager audiomanager;
	private SeekBar seekVol;
	
	/* ---------- pour remplir la spinner--------- */
	// spinner
	private Spinner urlSpinner;
	private String urlSpinnerValue;
	// on d�finit les variables pour g�rer le SharedPreferences
	private SharedPreferences urlArrayToString  = null;
	private SharedPreferences nameArrayToString = null;
	private String initialUrlString = null;
	private String initialNameString = null;
	private String[] initialUrlStringSplit = null;
	private String[] initialNameStringSplit = null;
	private ArrayAdapter<SpinnerRelation> urlAdapter = null;
	// on d�termine l'ArrayList qui g�rera le contenu de la spinner
	private ArrayList<SpinnerRelation> spinnerValues;
	//fin de mypref
	//final int MYPREF_OK=1000;
	
/* --------------------------------------------- ON CREATE  ----------------------------------------------- */
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        	setContentView(R.layout.home);
        	
        	spinnerValues = new ArrayList<SpinnerRelation>();
        	//Positionement d'un ecouteur sur les boutons
        	playstream = (Button) findViewById(R.id.play);
        	playstream.setOnClickListener(this);
        	stopstream = (Button) findViewById(R.id.pause);
        	stopstream.setOnClickListener(this);
        	

        	
        	urlSpinner = (Spinner)findViewById(R.id.urlSpinner);
    		// on dit dans quel fichier stocker les variables des sharedPreference (ici : "radio_preference")
    		urlArrayToString =  getSharedPreferences("radio_preference", 0);
    		nameArrayToString = getSharedPreferences("radio_preference", 0);
    		
    		/*--------------------------------------------------------------------
    		 * 		CONTROLE DU VOLUME DU MEDIA	
    		 --------------------------------------------------------------------*/
    		seekVol= (SeekBar)findViewById(R.id.volControl);
    		audiomanager= (AudioManager) getSystemService(AUDIO_SERVICE);
    		//Mise a l echelle de la seekbar (valeur max) pour STREAM_MEDIA
    		seekVol.setMax(audiomanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
    		//On position la seekbar au niveau de son courant
    		seekVol.setProgress(audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC));
    		//Definition de l ecouteur sur la seekbar, gestion du volume
    		seekVol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				public void onStopTrackingTouch(SeekBar seekBar) {
				}
				public void onStartTrackingTouch(SeekBar seekBar) {
				}
				public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
					//On met a jour le volume du tel de type AudioManager.STREAM_MUSIC, notification via le flag AudioManager.FLAG_SHOW_UI
					audiomanager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_SHOW_UI);
					seekBar.setProgress(progress);
					}
			});
}
protected void onResume() {
	super.onResume();
	// on remplit la spinner au d�marrage de l'activit� ou si elle est rappel�e.
	populateSpinner();
}
	   
/* --------------------------------------------- ON CLICK  ----------------------------------------------- */
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
// Actions evenement onClick de l'activit�
public void onClick(View arg0) {
	switch(arg0.getId()) {
		case R.id.play:
			if (!urlSpinnerValue.equals("")) {
				startPlaying(urlSpinnerValue);
				// on cache le bouton play pour afficher le bouton pause
				
				if(mp.isPlaying()) SwitchLayout2();
			}
			//Si url vide avertissement de l'utilisateur	
			else 
				Toast.makeText(this, "Url vide!", 50).show();
		break;
		case R.id.pause:
			
			pausePlaying();
			if(!mp.isPlaying())	SwitchLayout1();
		break;
	}
}



/* ------------------------------------------CREATION DU MENU  ----------------------------------------------- */
public boolean onCreateOptionsMenu(Menu menu) {
	//intancie le menu pointé par R.menu.menu et ajoute les vue (entrees du menu)
	MenuInflater inflatemenu = getMenuInflater();
	inflatemenu.inflate(R.menu.menu, menu);
		
	return super.onCreateOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {
	switch(item.getItemId()) {
		case R.id.newsfeed:
			//Intent vers l'activité des news feed
			final Intent GBrssreaderActivity = new Intent();
			GBrssreaderActivity.setClass(this,GBrssreader.class);
			startActivity(GBrssreaderActivity);
		break;
		case R.id.about:
			Toast.makeText(this, "About?", 100).show();
			final Intent aboutActivity = new Intent();
			aboutActivity.setClass(this,about.class);
			startActivity(aboutActivity);
		break;
		case R.id.exit:
			Toast.makeText(this, "Exit", 100).show();
			finish();
		break;
	}
	return super.onOptionsItemSelected(item);
}
	
/* --------------------------------------------- METHODES DU PLAYER  ----------------------------------------------- */
private void startPlaying(String urlStream) {
	mp= new MediaPlayer();
	try {
		mp.setDataSource(this, Uri.parse(urlStream));
		mp.prepare();
		mp.start();
		Toast.makeText(this, "Playing...", 80).show();
	} catch (IllegalArgumentException e) {
		e.printStackTrace();
	} catch (SecurityException e) {
		e.printStackTrace();
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
	
private void pausePlaying() {
	try {
		mp.stop();
		mp.reset();
		mp.prepare();
		Toast.makeText(this, "Pause...", 80).show();
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}	
}

/* (non-Javadoc)
 * @see android.app.Activity#finish()
 */
public void finish() {
//liberation des ressources
	if(mp != null) {
		mp.stop();
		mp.release();
		mp=null;
	}
		
	//IMPORTANT :
	//Objet mp à l'état neuf UTILISATION DE reset() (éviter le dl de données)!!!!
	// Destruction de mp
	super.finish();
}
/**
 * Masque le bouton Play et affiche le bouton pause
 */
private void SwitchLayout2() {
	// on d�finit nos relativeLayout
	RelativeLayout playLayout = (RelativeLayout) findViewById(R.id.relativeLayoutPlay);
	RelativeLayout pauseLayout = (RelativeLayout) findViewById(R.id.relativeLayoutPause);
	// Enable Layout 2 and Disable Layout 1
	playLayout .setVisibility(View.GONE);
	pauseLayout.setVisibility(View.VISIBLE);
}
/**
 * Masque le bouton pause et affiche le bouton play
 */
private void SwitchLayout1() {
	// on d�finit nos relativeLayout
	RelativeLayout playLayout = (RelativeLayout) findViewById(R.id.relativeLayoutPlay);
	RelativeLayout pauseLayout = (RelativeLayout) findViewById(R.id.relativeLayoutPause);
	// Enable Layout 1 & Disable Layout2
	playLayout.setVisibility(View.VISIBLE);
	pauseLayout.setVisibility(View.GONE);
}

/* --------------------------------------------- CLASS SPINNER RELATION  ----------------------------------------------- */
/**
 * On d�finit une nouvelle class pour pouvoir creer des relation Key -> value dans les drop-down (ou spinner)
 */
class SpinnerRelation {
	public String keyValue;
	public String displayValue;
	    	
	/**
	 * Cr�ation de l'objet
	 * @param keyValue
	 * @param displayValue
	 */
	public SpinnerRelation( String keyValue, String displayValue ) {
		this.keyValue = keyValue;
	    this.displayValue = displayValue;
	}
	/**
	 * 
	 * @return la key
	 */
	public String getKeyValue() {
	    return keyValue;
	}
	 /**
	  * 
	  * @return la valeur affichage dans la spinner
	  */
	 public String getDisplayValue() {
	    return displayValue;
	 }
	 /**
	  * Ce qui sera affich� dans le spinner
	  */
	 public String toString() {
	    return displayValue;
	 }
}


/* --------------------------------------------- REMPLIR LA SPINNER ----------------------------------------------- */
/**
 * Remplit la spinner et g�re les listeners associ�s
 */
private void populateSpinner() {
	    	
	// on importe les pr�f�rences
	initialUrlString = urlArrayToString.getString("url_array", "");
	initialNameString = nameArrayToString.getString("name_array", "");
	// on convertit en tableau de string
	initialUrlStringSplit = initialUrlString.split(",");
	initialNameStringSplit = initialNameString.split(",");
	    		
	// on supprime les �l�ments du tableau si jamais il s'agit de reprendre l'activit�
	spinnerValues.clear();
	//on ajoute en dur l url de gbradio
	spinnerValues.add(new SpinnerRelation(getString(R.string.radioStreamUrl),"GBradio"));
	//evite de creer une case vide si aucune pref
	if ((!initialNameString.equals(""))&(!initialUrlString.equals(""))) {	    		
		for (int i = 0; i < initialUrlStringSplit.length; i++) {
			spinnerValues.add(new SpinnerRelation(initialUrlStringSplit[i], initialNameStringSplit[i]));
		}
	}
	// on ajoute le dernier �l�ment qui permettra d'aller sur la gestion des url
	spinnerValues.add(new SpinnerRelation("add",getString(R.string.to_preference)));
		
	urlAdapter = new ArrayAdapter<SpinnerRelation>(this, android.R.layout.simple_spinner_item,spinnerValues);
	urlAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	urlSpinner.setAdapter(urlAdapter);
				
	urlSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			
			SpinnerRelation valueChosen = spinnerValues.get(position);
			// si on choisit l'�l�ment "add", on lance l'activit� MyPreferences
			if (valueChosen.getKeyValue().equals("add")) {
			      Intent monIntent = new Intent(getBaseContext(),MyPreferences.class);
			      startActivity(monIntent);
			     
			}
			// sinon on modifie l'url de lecture du flux
			else
			      urlSpinnerValue = valueChosen.getKeyValue();
		}
		public void onNothingSelected(AdapterView<?> parent) {
		}
	});
}	  

}